import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response =
      await client.get('https://jsonplaceholder.typicode.com/photos');
  // isolate，后台线程 --- foundation
  return compute(parsePhotos, response.body);
}

List<Photo> parsePhotos(String responseBody) {
  // 解析数据
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
  // 转换为列表
  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

class IsolateDataApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final String appTitle = 'Isolate Demo';
    return MaterialApp(
      title: appTitle,
      theme: ThemeData(primarySwatch: Colors.red),
      home: IsolateDataAppPage(title: appTitle),
    );
  }
}

class IsolateDataAppPage extends StatefulWidget {
  final String title;

  IsolateDataAppPage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() => IsolateDataAppPageState();
}

class IsolateDataAppPageState extends State<IsolateDataAppPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder(
          future: fetchPhotos(http.Client()),
          builder: (context, snapshot) {
            if (snapshot.hasError) print(snapshot.error);

            return snapshot.hasData
                ? PhotosList(photos: snapshot.data)
                : Center(
                    child: CircularProgressIndicator(),
                  );
          }),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;
  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: photos.length,
        itemBuilder: (context, index) {
          return Image.network(photos[index].thumbnailUrl);
        });
  }
}

class Photo {
  final int albumId;
  final int id;
  final String title;
  final String url;
  final String thumbnailUrl;

  Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  // 解析数据
  factory Photo.fromJson(Map<String, dynamic> json) {
    return Photo(
      albumId: json['albumId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      url: json['url'] as String,
      thumbnailUrl: json['thumbnailUrl'] as String,
    );
  }
}
